<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Java Swing dialogs</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Java, Swing, dialogs, tutorial, programming, Linux">
<meta name="description" content="This part of the Java Swing tutorial covers Java Swing dialogs.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Java Swing dialogs</h1>



<p>
Dialog windows or dialogs are an indispensable part of most modern GUI applications. 
A dialog is defined as a conversation between two or more persons. In a computer 
application a dialog is a window which is used to "talk" to the application. A dialog 
is used to input data, modify data, change the application settings etc. Dialogs are 
important means of communication between a user and a computer program.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
In Java Swing toolkit, we can create two kinds of dialogs. Custom dialogs 
and standard dialogs. <b>Custom dialogs</b> are dialogs, created by 
the programmer. They are based on the <code>JDialog</code> class. 
<b>Standard dialogs</b> preedefined dialogs available in the Swing 
toolkit. For example <code>JColorChooser</code> or 
<code>JFileChooser</code>.
These are dialogs for common programming tasks like showing text, 
receiving input , loading and saving files etc. They save programmer's 
time and enhance using some standard behaviour.
</p>

<p>
There are two basic types of dialogs. Modal and modeless. <b>Modal</b> 
dialogs block input to other top level windows. 
<b>Modeless</b> dialogs allow input to other windows. What type of dialog 
to use, depends on the circumstances. An open file dialog is a good example 
of a modal dialog. While choosing a file to open, no other operation should be permitted.
A typical modeless dialog is a find text dialog. 
It is handy to have the ability to move the cursor in the text control 
and define, where to start the finding of the particular text. 
</p>


<h2>A simple custom dialog</h2>

<p>
In the following example we create a simple custom dialog. It is a sample 
about dialog, found in most GUI applications, usually located in the help menu.  
</p>


<pre class="code">
package zetcode;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

class AboutDialog extends JDialog {

    public AboutDialog() {

        initUI();
    }

    public final void initUI() {

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        add(Box.createRigidArea(new Dimension(0, 10)));

        ImageIcon icon = new ImageIcon("notes.png");
        JLabel label = new JLabel(icon);
        label.setAlignmentX(0.5f);
        add(label);

        add(Box.createRigidArea(new Dimension(0, 10)));

        JLabel name = new JLabel("Notes, 1.23");
        name.setFont(new Font("Serif", Font.BOLD, 13));
        name.setAlignmentX(0.5f);
        add(name);

        add(Box.createRigidArea(new Dimension(0, 50)));

        JButton close = new JButton("Close");
        close.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        close.setAlignmentX(0.5f);
        add(close);

        setModalityType(ModalityType.APPLICATION_MODAL);

        setTitle("About Notes");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setSize(300, 200);
    }
}

public class SimpleDialog extends JFrame {

    public SimpleDialog() {

        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenu help = new JMenu("Help");
        help.setMnemonic(KeyEvent.VK_H);

        JMenuItem about = new JMenuItem("About");
        help.add(about);

        about.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                AboutDialog ad = new AboutDialog();
                ad.setVisible(true);
            }
        });

        menubar.add(file);
        menubar.add(help);
        setJMenuBar(menubar);

        setTitle("Simple Dialog");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                SimpleDialog sd = new SimpleDialog();
                sd.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The sample code will popup a small dialog box. The dialog will 
display an icon a text and one close button.
</p>

<pre class="explanation">
class AboutDialog extends JDialog {
</pre>

<p>
The custom dialog is based on the <code>JDialog</code> class.
</p>


<pre class="explanation">
setModalityType(ModalityType.APPLICATION_MODAL);
</pre>

<p>
Here we make the dialog modal. 
</p>


<pre class="explanation">
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
</pre>

<p>
Here we set the defaul close operation. 
</p>


<pre class="explanation">
AboutDialog ad = new AboutDialog();
ad.setVisible(true);
</pre>

<p>
Here we display the about dialog, from the menu of the main frame.
</p>


<img src="/img/gui/javaswing/simpledialog.png" alt="Simple custom dialog">
<div class="figure">Figure: Simple custom dialog</div>



<h2>Message boxes</h2>

<p>
Message boxes provide information to the user. 
</p>

<pre class="code">
package zetcode;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MessageBoxes extends JFrame {

    private JPanel panel;

    public MessageBoxes() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2));

        JButton error = new JButton("Error");
        JButton warning = new JButton("Warning");
        JButton question = new JButton("Question");
        JButton information = new JButton("Information");

        error.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Could not open file",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        });

        warning.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "A deprecated call",
                        "Warning", JOptionPane.WARNING_MESSAGE);
            }
        });

        question.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Are you sure to quit?",
                        "Question", JOptionPane.QUESTION_MESSAGE);
            }
        });

        information.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Download completed",
                        "Question", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        panel.add(error);
        panel.add(warning);
        panel.add(question);
        panel.add(information);

        add(panel);

        setTitle("Message Boxes");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MessageBoxes mb = new MessageBoxes();
                mb.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The example shows an error, question, warning and information message boxes.
</p>

<pre class="explanation">
panel.setLayout(new GridLayout(2, 2));
</pre>

<p>
We use a <code>GridLayout</code> layout manager to organize
buttons, that will popup message boxes.
</p>

<pre class="explanation">
JButton error = new JButton("Error");
JButton warning = new JButton("Warning");
JButton question = new JButton("Question");
JButton information = new JButton("Information");
</pre>

<p>
Here are the four buttons, that we will use.
</p>

<pre class="explanation">
JOptionPane.showMessageDialog(panel, "Could not open file", 
    "Error", JOptionPane.ERROR_MESSAGE);
</pre>

<p>
To create a message box, we call the <code>showMessageDialog</code> 
static method of the <code>JOptionPane</code> class. We provide 
the component name, message text, title and a message type. The message 
type is determined by the constant we choose.  Available constants are:
</p>

<ul>
<li>ERROR_MESSAGE</li>
<li>WARNING_MESSAGE</li>
<li>QUESTION_MESSAGE</li>
<li>INFORMATION_MESSAGE</li>
</ul>


<img src="/img/gui/javaswing/question.png" alt="Question message box"> </td>
<div class="figure">Figure: Question message box</div>


<h2>JFileChooser</h2>

<p>
<code>JFileChooser</code> is a standard dialog for selecting a 
file from the file system.
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooserDialog extends JFrame {

    private JPanel panel;
    private JTextArea area;

    public FileChooserDialog() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        ImageIcon open = new ImageIcon("open.png");

        JToolBar toolbar = new JToolBar();
        JButton openb = new JButton(open);

        openb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter("c files", "c");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(panel, "Open file");

                if (ret == JFileChooser.APPROVE_OPTION) {
                    File file = fileopen.getSelectedFile();
                    String text = readFile(file);
                    area.setText(text);
                }

            }
        });

        toolbar.add(openb);

        area = new JTextArea();
        area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JScrollPane pane = new JScrollPane();
        pane.getViewport().add(area);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.add(pane);
        add(panel);

        add(toolbar, BorderLayout.NORTH);

        setTitle("FileChooserDialog");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public String readFile(File file) {

        StringBuffer fileBuffer = null;
        String fileString = null;
        String line = null;

        try {
            FileReader in = new FileReader(file);
            BufferedReader brd = new BufferedReader(in);
            fileBuffer = new StringBuffer();

            while ((line = brd.readLine()) != null) {
                fileBuffer.append(line).append(
                        System.getProperty("line.separator"));
            }

            in.close();
            fileString = fileBuffer.toString();
        } catch (IOException e) {
            return null;
        }
        return fileString;
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                FileChooserDialog fcd = new FileChooserDialog();
                fcd.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The code example will demonstrate how to use a file chooser dialog in order 
to load file contents into the 
text area component. 
</p>

<pre class="explanation">
JFileChooser fileopen = new JFileChooser();
</pre>

<p>
This is the constructor of the file chooser dialog.
</p>

<pre class="explanation">
FileFilter filter = new FileNameExtensionFilter("c files", "c");
fileopen.addChoosableFileFilter(filter);
</pre>

<p>
Here we define the file filter. In our case, we will have c files with extension .c. 
We have also the default
All files option.
</p>

<pre class="explanation">
int ret = fileopen.showDialog(panel, "Open file");
</pre>

<p>
Here we show the file chooser dialog. Upon clicking on the open file button, 
the return value is equal to
<code>JFileChooser.APPROVE_OPTION</code>.
</p>

<pre class="explanation">
if (ret == JFileChooser.APPROVE_OPTION) {
    File file = fileopen.getSelectedFile();
    String text = readFile(file);
    area.setText(text);
}
</pre>

<p>
Here we get the name of the selected file. We read the contents of the 
file and set the text into the textarea. 
</p>


<img src="/img/gui/javaswing/filechooserdialog.png" alt="JFileChooser dialog">
<div class="figure">Figure: JFileChooser dialog</div>


<h2>JColorChooser</h2>

<p>
<code>JColorChooser</code> is a standard dialog for selecting a color.
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;


public class ColorChooserDialog extends JFrame {

    private JPanel panel;
    private JPanel display;

    public ColorChooserDialog() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        ImageIcon open = new ImageIcon("color.png");

        JToolBar toolbar = new JToolBar();
        JButton openb = new JButton(open);

        openb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JColorChooser clr = new JColorChooser();
                Color color = clr.showDialog(panel, "Choose Color",
                        Color.white);
                display.setBackground(color);
            }
        });

        toolbar.add(openb);

        display = new JPanel();
        display.setBackground(Color.WHITE);

        panel.setBorder(BorderFactory.createEmptyBorder(30, 50, 30, 50));
        panel.add(display);
        add(panel);

        add(toolbar, BorderLayout.NORTH);

        setTitle("ColorChooserDialog");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ColorChooserDialog ccd = new ColorChooserDialog();
                ccd.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In the example, we have a white panel. We will change the background color 
of the panel by selecting a color from
the color chooser dialog. 
</p>

<pre class="explanation">
JColorChooser clr = new JColorChooser();
Color color = clr.showDialog(panel, "Choose Color", Color.white);
display.setBackground(color);
</pre>

<p>
This code shows a color chooser dialog. The <code>showDialog()</code> 
method returns the selected color value. We change the display panel 
background to the newly selected color. 
</p>


<img src="/img/gui/javaswing/colorchooserdialog.png" alt="JColorChooser dialog">
<div class="figure">Figure: JColorChooser dialog</div>


<p>
In this part of the Java Swing tutorial, we have covered dialogs.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 25, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>